package cn.openea.perpartner.componet.web.service.importandexport;

import cn.openea.perpartner.common.core.utils.poi.ExcelUtil;
import cn.openea.perpartner.common.core.web.domain.AjaxResult;
import cn.openea.perpartner.componet.web.entity.dto.ImportErrMsgDTO;
import cn.openea.perpartner.componet.web.enums.ImportAndExportActions;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ysk
 * @version 1.0.1
 * @Description 导入导出处理抽象类
 * @createTime 2023年05月16日 17:33:00
 */
@Slf4j
@Component
public abstract class ImportAndExportAbstractService implements ImportAndExportService {


    @Override
    public AjaxResult importExcel(MultipartFile file, String action) {
        ImportAndExportActions importAndExportActions = ImportAndExportActions.getByCode(action);
        List<ImportErrMsgDTO> errMsgDTOS = null;
        try {
            errMsgDTOS = handleExcel(file, importAndExportActions);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("处理导入Excel文件失败，使用原因:{}", e.getMessage());
        }
        return AjaxResult.success(errMsgDTOS);
    }

    /**
     * 处理Excel
     *
     * @param file
     * @return
     */
    private List<ImportErrMsgDTO> handleExcel(MultipartFile file, ImportAndExportActions action) throws Exception {
        ExcelUtil excelUtil = new ExcelUtil<>(action.getTClass());
        List list = excelUtil.importExcel(file.getInputStream());
        List<ImportErrMsgDTO> errMsgDTOS = new ArrayList<>();
        list.parallelStream().forEach(item -> {
            try {
                ImportErrMsgDTO errMsgDTO = handleSingleExcel(item);
                if (errMsgDTO != null) {
                    errMsgDTOS.add(errMsgDTO);
                }
            } catch (Exception e) {
                log.error("处理单个导入失败");
            }
        });
        return errMsgDTOS;
    }

    /**
     * 处理单个Excel
     *
     * @param obj
     */
    protected ImportErrMsgDTO handleSingleExcel(@NonNull Object obj) {
        return null;
    }
}
